
import urllib2
import json

from django.shortcuts import render, render_to_response, redirect
from django.http import HttpResponse
from django.template import RequestContext, loader

from django.contrib.auth import login
from django.db.utils import IntegrityError
from django.core.files.uploadedfile import SimpleUploadedFile

from django.conf import settings

from django.db.models import get_model
import re

_DEFAULT_PASS = 'aka5bdu_098'

class AuthVkPoint1Error( Exception ): pass
class AuthVkPoint2Error( Exception ): pass
class AuthVkPoint3Error( Exception ): pass

def _get_vk_username( user_id ):
	return 'vk_{0}'.format( user_id )

def get_fb_username( username ):
	return "fb_{0}".format( username )

def view2( request ):
	return redirect( '/' )

def _get_user_model():
	user_model_match = settings.MYAUTH_USER_MODEL.split( '.' )
	user_app_label = user_model_match[ 0 ]
	user_model_label = user_model_match[ 1 ]

	user_model = get_model( user_app_label, user_model_label )

	return user_model


def vk_view( request ):
	get = request.GET
		
	if 'error' in get: 
		if get[ 'error' ] == "access_denied" and 'error_reason' in get and get[ 'error_reason' ] == "user_denied":
			out = { 'action': "cancel" }
		else:
			raise AuthVkPoint1Error( "get={0}".format( get ) )
	elif 'code' in get:
		code = get[ 'code' ]

		url = "https://oauth.vk.com/access_token?client_id={0}&client_secret={1}&code={2}&redirect_uri=http://{3}/myauth/vk".format( settings.MYAUTH_VK_ID, settings.MYAUTH_VK_KEY, code, settings.DOMAIN )

		print "# url='{0}'".format( url )

		f = urllib2.urlopen( url )
		result = json.loads( f.read() )

		if 'error' in result:
			raise AuthVkPoint2Error( "result={0}".format( result ) )

		access_token = result[ 'access_token' ]
		user_id = result[ 'user_id' ]
		social_id = _get_vk_username( user_id )

		user_model = _get_user_model()

		try:
			user = user_model.objects.get( social_id = social_id )
			# the next line: http://stackoverflow.com/questions/2787650/manually-logging-in-a-user-without-password
			user.backend = 'django.contrib.auth.backends.ModelBackend'
			login( request, user )
			out = { 'action': "login" }
		except user_model.DoesNotExist:			
			f = urllib2.urlopen( "https://api.vk.com/method/users.get?uids={0}&fields=first_name,last_name,photo_big,photo,nickname&access_token={1}".format( user_id, access_token ) )
			result = json.loads( f.read() )

			if 'error' in result:
				raise AuthVkPoint3Error( "result={0}".format( result ) )

			info = result[ 'response' ][ 0 ]
			first_name = info[ 'first_name' ]
			last_name = info[ 'last_name' ]
			try:
				user = user_model.objects.get( social_id = social_id )
			except user_model.DoesNotExist:
				user = user_model.objects.create( social_id = social_id )		
				user.set_password( _DEFAULT_PASS )
				
			user.first_name = first_name
			user.last_name = last_name				

			# now image does not load			
			
			# the next - handle it later
			if 'photo_big' in info and info[ 'photo_big' ] != "":
				user.save_photo( info[ 'photo_big' ] )
			if 'photo' in info and info[ 'photo' ] != "":
				user.save_thumbnail( info[ 'photo' ] )

			user.save()

			user.backend = 'django.contrib.auth.backends.ModelBackend'
			login( request, user )

			out = { 'action': "register" }

	t = loader.get_template( 'vk.html' )
	c = RequestContext( request, out )

	out.update( { 'register_redirect': settings.MYAUTH_REGISTER_REDIRECT, 'login_redirect': settings.MYAUTH_LOGIN_REDIRECT } )

	print "# out={0}".format( out )

	return HttpResponse(	t.render(c),
       						content_type = 'text/html' )

def fb_view( request ):
	# in this state you could log in as any user
		
	# check if user with the username exists...

	# may be get instead of post
	post = request.POST
	user_model = _get_user_model()
	social_id = get_fb_username( post[ 'id' ] )

	try:
		user = user_model.objects.get( social_id = social_id )
	except:			
		user = user_model.objects.create( social_id = social_id )
		user.set_password( _DEFAULT_PASS )
		user.first_name = post[ 'first_name' ]
		user.last_name = post[ 'last_name' ]
		username = post[ 'username' ]
		user.save_photo( "https://graph.facebook.com/{0}/picture?type=large".format( username ) )
		user.save_thumbnail( "https://graph.facebook.com/{0}/picture?type=square".format( username ) )

		user.save()

		link = settings.MYAUTH_REGISTER_REDIRECT
	else:			
		user = user_profile.user
		link = settings.MYAUTH_LOGIN_REDIRECT
	
	user.backend = 'django.contrib.auth.backends.ModelBackend'
	login( request, user )

	t = loader.get_template( 'fb-link.json' )
	c = RequestContext( request, { 'link': link } )

	return HttpResponse(	t.render(c),
       						content_type = 'text/html' )
			